<?php
declare (strict_types = 1);

namespace app\home\model;

class Menus extends \app\common\model\Menus
{
    public function getMenuUrlAttr($value, $data)
    {
        if (!empty($value)) $value = DS . trim($value, '/');
        else $value = '/' . $data['menu_id'];
        return $value;
    }

    private function webList()
    {
        return $this->deleteWhere()->where('is_show', 1)->order('menu_sort', 'ASC')->select();
    }

    public function getWebList()
    {
        $list = $this->webList();
//        foreach ($list as &$value){
//            if (!empty($value->menu_url)) $value->menu_url = DS . trim($value->menu_url, '/');
//            else $value->menu_url = url('/' . $value->menu_id);
//        }
        return list_to_tree($list->toArray());
    }

    public function getDetailByIdOrUrl(string $str)
    {
        return $this->deleteWhere()
            ->where('menu_id|menu_url', '=', $str)
            ->whereOr(function($query) use ($str){
                $query->where('menu_url', '=', $str)->whereOr('menu_url', '=', '/' . $str);
            })
            ->whereOr('menu_name', '=', $str)
            ->find();
    }

    public function getChildIds(int $parent_id, array $list = []): array
    {
        $arr_ids = [$parent_id];
        if (empty($list)) $list = $this->webList()->toArray();
        foreach ($list as $key => $value){
            if ($value['parent_id'] == $parent_id) {
                unset($list[$key]);
                $sub_ids = $this->getChildIds($value['menu_id'], $list);
                !empty($sub_ids) && $arr_ids = array_merge($arr_ids, $sub_ids);
            }
        }
        return $arr_ids;
    }
}
